(function () {/**
 * Created by  on 2017/1/20.
 */
var commonObject = function() {
    this.globalHost='http://kingw.xicp.io:10192/';
    // this.globalHost='http://192.168.1.219:8080/';
    // this.globalHost='http://192.168.2.109:8080/';
    // this.globalHost='http://192.168.1.89:8080/';
    this.queryVillageSaleHouse='s/saleHouseQuery/queryVillageSaleHouse';//查询小区列表接口
    this.queryVillageByName='s/saleHouseQuery/queryVillageByName';//查询房屋列表接口
    this.getSaleHouseById='s/saleHouseQuery/getSaleHouseById';//查询房屋详情接口
    this.dealQueryVillageByName='s/houseDeal/queryVillageByName';//成交小区查询接口；
    this.dealQueryVillageSaleHouse='s/houseDeal/queryVillageDealHouse';//成交小区房屋列表接口；
    this.lpHost='http://121.40.178.164:4040/agent-service';
    // this.lpHost='http://121.40.201.35:4040/agent-service';
    // this.lpHost='http://120.55.66.146:8080/agent-service';
    this.loginPort='/api/user/login.do';
};
commonObject.prototype = {
    checkApp:function(){
        var self=this;
        var result="";
        $.each(self.popularApp,function(idx,ele){
            if(navigator.userAgent.indexOf(ele)>-1){
                result=true;
                return;
            }
        });
       return result;
    },
    isInWX:function(){
        var slef=this;
        if(navigator.userAgent.indexOf('MQQBrowser')>-1){
            return true;
        }
        return false;
    },
    getQueryString:function(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURI(r[2]);
        return null;
    },
    getSendDataByForm: function(selector) {
        var list = $(selector).serializeArray(),
            json = {};
        $.each(list, function(i, I) {
            var tag = $(selector).find('[name=' + I.name + ']')[0].tagName;
            if(tag === 'TEXTAREA') {
                I.value = I.value.replace(/\r\n/g, "\\r\\n");
            }
            if (!json[I.name]) {
                json[I.name] = I.value
            } else {
                json[I.name] = json[I.name] + ',' + I.value;
            }
        });
        return json;
    },
    getToken: function() {
        var self=this;
        var loginData = self.getLocalData("houseSearchAgentInfoToken");
        if (!loginData) {
            window.location.href = './login.html';
            return false;
        }
        return loginData.token;
    },
    setLocalStorage: function(key, value) {
        if (window.localStorage) {
            localStorage.setItem(key, value);
        }
    },
    setSessionStorage: function(key, value) {
        if (window.sessionStorage) {
            sessionStorage.setItem(key, value);
        }
    },
    getLocalData: function(key) {
        if (window.localStorage) {
            var data = localStorage.getItem(key);
            data = JSON.parse(data);
            return data;
        }
    },
    getSessionData: function(key) {
        if (window.sessionStorage) {
            var data = sessionStorage.getItem(key);
            data = JSON.parse(data);
            return data;
        }
    },
	//添加cookie                                                          
	// setCookie: function(name, value, time) {
	// 	//console.log(name,value)
	// 	var date = new Date();
 //        // date.setTime(date.getTime() + time*24*60*60*1000); //设置date的天为现在加上间隔
	// 	date.setTime(date.getTime() + time*1000); //设置date的天为现在加上间隔
 //        console.log(date);
 //        console.log(date.setTime(date.getTime() + time*24*60*60*1000));
	// 	document.cookie = name + "=" + value + ";expires=" + date;
	// },
    setCookie: function(key, value, daysToLive) {
            var cookie = key + '=' + encodeURIComponent(value);
            if (typeof daysToLive == 'number') {
                cookie += ';max-age=' + (daysToLive * 60 * 60 );
            }
            document.cookie = cookie;
        },
	//删除cookie
	removeCookie: function(name) {
		this.setCookie(name, 1, -1); //设置cookie过期，则该条cookie被删除
	},

	//获取cookie的值
	getCookie: function(name) {
		var str = document.cookie;
		var arr = str.split("; "); //分割成 key1=value1; key2=value2; key3=value3 
		for (var i = 0; i < arr.length; i++) { //遍历每个键值对
			var arr1 = arr[i].split("="); //得到存储键值对的数组  [key,value]
			if (arr1[0] == name) { //找到则返回对应的值
				return arr1[1];
			}
		}
		return ""; //找不到，返回空值
	},
    buildNormalSwipe:function (options) {
        var self=this;
        //获取相关dom元素
        var $sliderPanel=$(options.sliderPanel);
        var slideWidth=$sliderPanel.width();//获取屏幕宽度值
        //获取轮播图容器
        var $sliderUl=options.sliderContainer?$(options.sliderContainer):$sliderPanel.find(".slider").length>0?$sliderPanel.find(".slider"):$sliderPanel.find("ul");
        //获取计数点
        var $countingOl=options.sliderCounting?$(options.sliderCounting):$sliderPanel.find(".counting").length>0?$sliderPanel.find(".counting"):$sliderPanel.find("ol");
        //判断是否有计数点
        var hasCounting=$countingOl.length||0;
        var dataType=options.dataType||"image";
        var countingType=options.countingType||"point";
        var imgPath=options.imgPath||"";//图片的目录
        var data=options.data||[]; // 图片的数据源
        var delayTime=parseInt(options.moveDelay)||2000;//获取设置轮播图的间隔时间,默认是2s
        var dataLength=data.length||0; // 图片数据源的长度
        var sliderItemsLength=dataLength+2; //轮播图内的轮播项数量
        var $ImagesWidth=sliderItemsLength*100; //计算轮播图容器的宽度
        $sliderUl.css({'width':($ImagesWidth+"%")});//设置轮播容器的宽度
        //声明空数组，sliderItems放置轮播图的每一项图片，countingItems计数用来统计
        var sliderItems=[];
        var countingItems=[];
        var index=1;//获取当前默认计数的索引
        //遍历数据源，组装数据
        if (dataLength) {
            if(dataType==='background'){
                if(hasCounting && countingType === "point"){
                    buildPointCountingByBackground(data);
                    setPointCountingStyleByImage();
                }
                if(hasCounting && countingType === "number"){
                    buildNumberCountingByBackground(data);
                    setNumberCountingStyleByImage();
                }
            }
            if(dataType==='image'){
                if(hasCounting && countingType === "point"){
                    buildPointCountingByImage(data);
                    setPointCountingStyleByImage();
                }
                if(hasCounting && countingType === "number"){
                    buildNumberCountingByImage(data);
                    setNumberCountingStyleByImage();
                }
            }
            if(dataType==='DOM'){
                if(hasCounting && countingType === "point"){
                    buildPointCountingByDOM(data);
                    setPointCountingStyleByDOM();
                }
                if(hasCounting && countingType === "number"){

                }
            }
            sliderItems.unshift(sliderItems[sliderItems.length-1]);
            sliderItems.push(sliderItems[1]);
            //为轮播容器内添加dom结构，并设置每一项的宽度
            $sliderUl.html(sliderItems.join(""));
            $sliderUl.css('left',-index*slideWidth+"px");
            //noinspection JSValidateTypes
            var $sliderLis = $sliderUl.children("li");
            $sliderLis.css({'width': (100 / sliderItemsLength + "%")});

        }
        var timer=null;
        autoMove();
        //noinspection JSValidateTypes
        var $countingLis=$countingOl.children("li");

        $sliderUl.on("transitionend",function () {
            index=index>=dataLength+1?1:index;
            index=index <=0?dataLength:index;
            self.removeTransition($sliderUl,"trans");
            self.moveColumn($sliderUl,-index * slideWidth);
            if(hasCounting && countingType === "point"){

                $countingLis.eq(index-1).addClass("now").siblings("li").removeClass("now");
            }
            if(hasCounting && countingType === "number"){
                $("#current-index").html(index);
            }
        });
        var start = 0;
        var end = 0;
        var distanceFinal = 0;
        var move = 0;
        var moveDistance=0;

        $sliderUl.on('touchstart', function(e) {
            e.stopPropagation();
            // e.preventDefault();
            timerChecked(timer);
            self.removeTransition($sliderUl,"trans");
            start=e.touches[0].clientX;
        });

        $sliderUl.on('touchmove', function(e) {
            e.stopPropagation();
            e.preventDefault();
            move=e.touches[0].clientX;
            moveDistance = move - start;
            index=index>=dataLength+1?1:index;
            index=index <=0?dataLength:index;
            var num = moveDistance + -index * slideWidth;

            self.removeTransition($sliderUl,"trans");
            self.moveColumn($sliderUl,num);
        });
        $sliderUl.on('touchend', function(e) {
            e.stopPropagation();
            // e.preventDefault();
            end = e.changedTouches[0].clientX;
            distanceFinal = end - start;
            if (Math.abs(distanceFinal) > (slideWidth * 1 / 3)) {
                if (distanceFinal < 0) {
                    index++;
                } else {
                    index--;
                }
            }
            self.moveColumn($sliderUl,-index * slideWidth);
            self.addTransition($sliderUl,"trans");
            autoMove();
        });
        //tools
        function buildPointCountingByDOM(data) {
            $.each(data, function (idx, ele) {
                sliderItems.push('<li>'+ele+'</li>');
                countingItems.push("<li></li>");
            });
        }

        function buildNumberCountingByBackground(data) {
            $.each(data, function (idx, ele) {
                sliderItems.push('<li style="background-image:url('+ imgPath + ele+')"></li>');
            });
            countingItems.push("<li><span id='current-index'>"+index+"</span> / <span id='total-count'>"+dataLength+"</span></li>");
        }

        function buildPointCountingByBackground(data) {
            $.each(data, function (idx, ele) {
                sliderItems.push('<li style="background-image:url('+ imgPath + ele+')"></li>');
                countingItems.push("<li></li>");
            });
        }

        function buildPointCountingByImage(data) {
            $.each(data, function (idx, ele) {
                sliderItems.push('<li><img src="' + imgPath + ele + '"></li>');
                countingItems.push("<li></li>");
            });
        }

        function buildNumberCountingByImage(data) {
            $.each(data, function (idx, ele) {
                sliderItems.push('<li><img src="' + imgPath + ele + '"></li>');
            });
            countingItems.push("<li><span id='current-index'>"+index+"</span> / <span id='total-count'>"+dataLength+"</span></li>");
        }

        function setPointCountingStyleByImage() {
            //为轮播计数添加dom结构，并初始化当前默认的计数点
            $countingOl.addClass("point").html(countingItems.join(""));
            var countingOlWidth=$countingOl.width();//获取计数点ol的宽度
            //noinspection JSValidateTypes
            var $countingLis=$countingOl.children("li");
            var unitPointWidth=$countingLis.width();
            var unitPointMargin=((countingOlWidth/dataLength)-unitPointWidth)/2;
            $countingLis.css({margin:"0 "+unitPointMargin+"px"});
            $countingLis.eq(0).addClass('now');
        }

        function setNumberCountingStyleByImage() {
            $countingOl.addClass("number-counting").html(countingItems.join(""));
        }
        function setPointCountingStyleByDOM() {
            $countingOl.addClass("point").html(countingItems.join(""));
            //noinspection JSValidateTypes
            $countingOl.children("li").eq(0).addClass('now');
        }

        function autoMove() {
            timerChecked();
            if(delayTime>=0 && !!options.autoPlay){
                timer = setInterval(function () {
                    index++;
                    self.addTransition($sliderUl,"trans");
                    self.moveColumn($sliderUl,-index * slideWidth);
                },delayTime);
            }
            return false;
        }
        function timerChecked() {
            return !!timer?clearInterval(timer):null;
        }
    },
    removeTransition:function (selector,className) {
        $(selector).removeClass(className);
    },
    addTransition:function (selector,className) {
        var selfSelector=$(selector);
        if(!selfSelector.hasClass(className)){
            selfSelector.addClass(className);
        }
    },
    moveColumn:function (selector,num) {
        num=(num+"").indexOf("%")>-1?num:num+"px";
        $(selector).css('left',num);
    },
    moveRow:function (selector,num) {
        num=(num+"").indexOf("%")>-1?num:num+"px";
        $(selector).css('top',num);
    }
};
window.common = new commonObject();
}).call(this);